/*
* Licensed under the MIT License
* 
* Copyright (c) 2010 Kay Kreuning
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* 
* http://code.google.com/p/as3hyvesapi
*/
package nl.hyves.api.authorization
{
	import flash.events.Event;
	import flash.net.SharedObject;
	import flash.utils.setTimeout;
	
	import nl.hyves.api.oauth.IAuthorizer;
	import nl.hyves.api.oauth.IOAuth;
	import nl.hyves.api.oauth.OAuthToken;
	
	public class StoredTokenAuthorization implements IAuthorizer
	{
		private static const SO_IDENTIFIER:String = "nl.hyves.api.authorization.StoredTokenAuthorization.SO_IDENTIFIER";
		
		public static function clear():void
		{
			SharedObject.getLocal(SO_IDENTIFIER).clear();
		}
		
		private var backup:IAuthorizer;
		private var so:SharedObject;
		private var oauth:IOAuth;
		
		public function StoredTokenAuthorization(backup:IAuthorizer)
		{
			this.backup = backup;
			
			so = SharedObject.getLocal(SO_IDENTIFIER);
		}
		
		public function authorize(oauth:IOAuth):void
		{
			this.oauth = oauth;
			
			if (so.data.userId != null && so.data.methods != null)
			{
				if (new Date().getTime() >= so.data.expireDate.getTime())
				{
					// Token is expired, ask for a new one.
					
					clear();
					authorize(oauth);
					
					return;
				}
				
				// Delay so that event listeners on the Service van catch up
				setTimeout(oauth.updateCredentials, 1, new OAuthToken(
					so.data.token,
					so.data.tokenSecret,
					so.data.userId,
					so.data.methods,
					so.data.expireDate
				));
			}
			else
			{
				oauth.addEventListener(Event.COMPLETE, onAuthorized);
				
				backup.authorize(oauth);
			}
		}
		
		private function onAuthorized(event:Event):void
		{
			var token:OAuthToken = oauth.getCredentials();
			
			so.data.token = token.token;
			so.data.tokenSecret = token.secret;
			so.data.userId = token.userId;
			so.data.methods = token.methods;
			so.data.expireDate = token.expireDate;
			
			so.flush();
		}
	}
}